package com.sgb.kjwl.view.ui.activity.self.packers;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;

import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.AtSelfEmploymentApplyEditBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.packers.EmploymentApplyEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.view.widget.WorkTypeSelectWindow;
import com.sgb.kjwl.viewmodel.self.packers.SelfEmploymentApplyEditModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * description:用户中心-用工报名编辑
 *
 * @author LiWei
 * @date 2020-11-30
 */
public class SelfEmploymentApplyEditActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {

    private AtSelfEmploymentApplyEditBinding binding;

    @Inject
    SelfEmploymentApplyEditModel viewModel;

    private EmploymentApplyEntity entity;

    private List<PickSelectEntity> pickProjectCategory;
    private List<PickSelectEntity> pickWorkType;
    private List<PickSelectEntity> pickPackerType;

    private List<String> workTypeListNo;

    /**
     * 一级联动数据
     */
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    /**
     * 二级联动数据
     */
    private final List<List<AddressEntity<List<AddressEntity>>>> opt2 = new ArrayList<>();
    /**
     * 三级联动数据
     */
    private final List<List<List<AddressEntity>>> opt3 = new ArrayList<>();

    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private boolean isLoaded = false;

    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;

    public static void start(Context context, String no, int requestCode) {
        Intent intent = new Intent();
        intent.putExtra("no", no);
        intent.setClass(context, SelfEmploymentApplyEditActivity.class);
        ((SelfEmploymentApplyActivity) context).startActivityForResult(intent, requestCode);
    }

    @Override
    protected boolean statusBarDark() {
        return false;
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder().appComponent(appComponent).
                selfModule(new SelfModule(this)).
                build().
                inject(this);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.at_self_employment_apply_edit);
        binding.setViewModel(null);
        binding.btnCancel.setOnClickListener(this);
        binding.btnRelease.setOnClickListener(this);
        binding.etCategoryName.setOnWholeItemClickListener(this);
        binding.etWorkType.setOnWholeItemClickListener(this);
        binding.etPackerType.setOnWholeItemClickListener(this);
        binding.etAddress.setOnWholeItemClickListener(this);
        binding.etContactPhone.setInputType(InputType.TYPE_CLASS_PHONE);
        binding.etContactPhone.setInfilterType(ItemInputTextView.TYPE_PHONE);
        binding.etWorkerNum.setInputType(InputType.TYPE_CLASS_NUMBER);
    }

    @Override
    protected void init() {
        entity = new EmploymentApplyEntity();
        if (!TextUtils.isEmpty(getIntent().getStringExtra("no"))) {
            viewModel.getDetailEmploymentApply(getIntent().getStringExtra("no"));
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_cancel) {
            finish();
        } else if (id == R.id.btn_release) {
            if (TextUtils.isEmpty(binding.etCategoryName.getContent())) {
                MToast.showToast(this, binding.etCategoryName.getContent_edt().getHint().toString());
                return;
            }
            if (TextUtils.isEmpty(binding.etWorkType.getContent())) {
                MToast.showToast(this, binding.etWorkType.getContent_edt().getHint().toString());
                return;
            }
            if (TextUtils.isEmpty(binding.etContactName.getContent())) {
                MToast.showToast(this, binding.etContactName.getContent_edt().getHint().toString());
                return;
            }
            if (TextUtils.isEmpty(binding.etContactPhone.getContent())) {
                MToast.showToast(this, binding.etContactPhone.getContent_edt().getHint().toString());
                return;
            }
            if (TextUtils.isEmpty(binding.etPackerType.getContent())) {
                MToast.showToast(this, binding.etPackerType.getContent_edt().getHint().toString());
                return;
            }
            if (TextUtils.isEmpty(binding.etAddress.getContent())) {
                MToast.showToast(this, binding.etAddress.getContent_edt().getHint().toString());
                return;
            }
            if (TextUtils.isEmpty(binding.etWorkerNum.getContent())) {
                MToast.showToast(this, binding.etWorkerNum.getContent_edt().getHint().toString());
                return;
            }
            if (!CheckUtils.isMobile(binding.etContactPhone.getContent().trim())) {
                MToast.showToast(this, "请填写正确的联系电话");
                return;
            }
            entity.setContact(binding.etContactName.getContent());
            entity.setContactPhone(binding.etContactPhone.getContent());
            entity.setConstructionNumber(binding.etWorkerNum.getContent());
            viewModel.employmentEditApply(entity);
        }
    }

    @Override
    public void OnWholeItemClick(View view) {
        int id = view.getId();
        if (id == R.id.et_category_name) {
            if (null == pickProjectCategory) {
                viewModel.getProTypeList();
            } else {
                showProjectCategoryPop(pickProjectCategory);
            }
        } else if (id == R.id.et_work_type) {
            if (null == pickWorkType) {
                viewModel.getWorkType();
            } else {
                showPickWorkTypePop(pickWorkType);
            }
        } else if (id == R.id.et_packer_type) {
            if (null == pickPackerType) {
                viewModel.getEmploymentType();
            } else {
                showPickPackerTypePop(pickPackerType);
            }
        } else if (id == R.id.et_address) {
            if (addressEntityList != null) {
                showCityPop();
            } else {
                viewModel.getAddressModel();
            }
        }
    }

    public void updateWorkerEntity(EmploymentApplyEntity data) {
        if (data != null) {
            entity = data;
            binding.setViewModel(entity);
        }
    }

    public void employmentApplySuccess() {
        setResult(RESULT_OK);
        finish();
    }

    public void showProjectCategoryPop(List<PickSelectEntity> list) {
        if (null == pickProjectCategory) {
            pickProjectCategory = new ArrayList<>();
            pickProjectCategory.addAll(list);
        }
        if (pickProjectCategory.size() > 0) {
            OptionsPickerView projectCategoryOption = new OptionsPickerBuilder(SelfEmploymentApplyEditActivity.this, (options1, options2, options3, v) -> {
                binding.etCategoryName.setContent(pickProjectCategory.get(options1).getProjectscale());
                entity.setCategoryNo(pickProjectCategory.get(options1).getNo());
            }).setCancelColor(ContextCompat.getColor(this, R.color.color_666666)).setTitleColor(ContextCompat.getColor(this, R.color.color_969696)).build();
            projectCategoryOption.setPicker(pickProjectCategory);
            projectCategoryOption.setSelectOptions(0);
            projectCategoryOption.show();
        }
    }

    public void showPickWorkTypePop(List<PickSelectEntity> list) {
        if (null == pickWorkType) {
            pickWorkType = new ArrayList<>();
            pickWorkType.addAll(list);
        }
        if (pickWorkType.size() > 0) {
            WorkTypeSelectWindow typeSelectWindow = new WorkTypeSelectWindow(SelfEmploymentApplyEditActivity.this);
            typeSelectWindow.setSelectResultClick((pickSelectEntities, name) -> {
                workTypeListNo = new ArrayList<>();
                for (PickSelectEntity pickSelectEntity : pickSelectEntities) {
                    workTypeListNo.add(pickSelectEntity.getNo());
                }
                entity.setWorkType(workTypeListNo);
                binding.etWorkType.setContent(name);
            });
            typeSelectWindow.setBgView(binding.grayLayout);
            typeSelectWindow.setWorkTypeData(list);
            typeSelectWindow.showPopwindow(binding.etWorkType);
        }
    }

    public void showPickPackerTypePop(List<PickSelectEntity> list) {
        if (null == pickPackerType) {
            pickPackerType = new ArrayList<>();
            pickPackerType.addAll(list);
        }
        if (pickPackerType.size() > 0) {
            OptionsPickerView projectCategoryOption = new OptionsPickerBuilder(SelfEmploymentApplyEditActivity.this, (options1, options2, options3, v) -> {
                binding.etPackerType.setContent(pickPackerType.get(options1).getProjectscale());
                entity.setEmploymentType(Integer.parseInt(pickPackerType.get(options1).getNo()));
            }).setCancelColor(ContextCompat.getColor(this, R.color.color_666666)).setTitleColor(ContextCompat.getColor(this, R.color.color_969696)).build();
            projectCategoryOption.setPicker(pickPackerType);
            projectCategoryOption.setSelectOptions(0);
            projectCategoryOption.show();
        }
    }

    /**
     * 所在地区选择
     * @param data 地区的数据
     */
    public void showAddressPop(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        this.addressEntityList = data;
        if (isLoaded) {
            showCityPop();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    @SuppressWarnings("unchecked")
    public void showCityPop() {
        //条件选择器
        CityPickView cityOption = new CityPickBuilder(SelfEmploymentApplyEditActivity.this, (options1, options2, options3, v) -> {
            String areaName;
            if (opt3.get(options1).get(options2).get(options3) == null) {
                areaName = "";
            } else {
                areaName = opt3.get(options1).get(options2).get(options3).getName();
                cityPosition3 = options3;
                entity.setAreaNo(opt3.get(options1).get(options2).get(options3).getNo());
                entity.setAreaName(areaName);
            }
            String content = addressEntityList.get(options1).getName()
                    + opt2.get(options1).get(options2).getName()
                    + areaName;
            binding.etAddress.setContent(content);
            cityPosition1 = options1;
            cityPosition2 = options2;
            entity.setProvinceName(addressEntityList.get(options1).getName());
            entity.setProvinceNo(addressEntityList.get(options1).getId());
            entity.setCityName(opt2.get(options1).get(options2).getName());
            entity.setCityNo(opt2.get(options1).get(options2).getNo());
        }).setCancelColor(ContextCompat.getColor(this, R.color.color_666666)).setTitleColor(ContextCompat.getColor(this, R.color.color_969696)).build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }

    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {
                        //如果已创建就不再重新创建子线程了
                        thread = new Thread(() -> {
                            // 子线程中解析省市区数据
                            initJsonData();
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showCityPop();
                    isLoaded = true;
                    thread = null;
                    break;
                default:
                    break;
            }
            return false;
        }
    });

    private void initJsonData() {
        //城市列表
        @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") List<AddressEntity<List<AddressEntity>>> cityList;
        //区域列表
        List<List<AddressEntity>> areaList;
        for (int x = 0; x < addressEntityList.size(); x++) {
            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            if (entity != null && entity.getProvinceName() != null && entity.getProvinceName().equals(addressEntityList.get(x).getName())) {
                cityPosition1 = x;
            }
            opt2.add(addressEntityList.get(x).getChildren());
            for (int i = 0; i < addressEntityList.get(x).getChildren().size(); i++) {
                cityList.add(addressEntityList.get(x).getChildren().get(i));
                List<AddressEntity> cityAreaList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (addressEntityList.get(x).getChildren().get(i).getChildren() == null
                        || addressEntityList.get(x).getChildren().get(i).getChildren().size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(addressEntityList.get(x).getChildren().get(i).getChildren());
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
        if (entity != null) {
            if (entity.getCityName() != null) {
                for (int x2 = 0; x2 < opt2.size(); x2++) {
                    if (entity.getCityName().equals(addressEntityList.get(cityPosition1).getChildren().get(x2).getName())) {
                        cityPosition2 = x2;
                        break;
                    }
                }
            }
            if (entity.getAreaName() != null) {
                for (int x3 = 0; x3 < opt3.size(); x3++) {
                    if (entity.getAreaName().equals(addressEntityList.get(cityPosition1).getChildren().get(cityPosition2).getChildren().get(x3).getName())) {
                        cityPosition3 = x3;
                        break;
                    }
                }
            }
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }
}
